package 下一个更大元素Ⅰ;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Stack;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 下一个更大元素 I
 * @date 2022/11/26 16:38
 */
public class Demo496 {
    public static void main(String[] args) {
        int[] nums={4,1,2};
        int[] nums2={1,3,4,2};
        int[] ints = nextGreaterElement2(nums, nums2);
        System.out.println(ints);
    }
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] res=new int[nums1.length];
        Arrays.fill(res,-1);
        for (int i = 0; i < nums1.length; i++) {
            boolean flag=false;
            for (int j = 0; j < nums2.length; j++) {
                if(nums1[i]==nums2[j]){
                    flag=true;
                }
                if(flag&&nums2[j]>nums1[i]){
                    res[i]=nums2[j];
                    break;
                }
            }
        }
        return res;
    }

    //单调栈解法，从栈顶，到栈底，单调递增
    public  static int[] nextGreaterElement2(int[] nums1, int[] nums2) {
        Stack<Integer> temp = new Stack<>();
        int[] res = new int[nums1.length];
        Arrays.fill(res,-1);
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0 ; i< nums1.length ; i++){
            hashMap.put(nums1[i],i);
        }
        temp.add(0);
        for (int i = 1; i < nums2.length; i++) {
            if (nums2[i] <= nums2[temp.peek()]) {
                temp.add(i);
            } else {
                while (!temp.isEmpty() && nums2[temp.peek()] < nums2[i]) {
                    if (hashMap.containsKey(nums2[temp.peek()])){
                        Integer index = hashMap.get(nums2[temp.peek()]);
                        res[index] = nums2[i];
                    }
                    temp.pop();
                }
                temp.add(i);
            }
        }

        return res;
    }
}
